package com.icesoft.system.safe.service;

import com.icesoft.framework.core.cache.RedisCacheManager;
import com.icesoft.framework.core.exception.BusinessException;
import com.icesoft.system.safe.model.CryptoKeyPair;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Component
public class CryptoKeyPairRepository {

	@Resource
	private RedisCacheManager redisService;

	/**
	 * 通过KeyId获取密钥信息
	 *
	 * @return CryptoKeyPair
	 */
	@Nullable
	public Map<String, CryptoKeyPair> find() {
		return redisService.getCacheMap("cryptoKeyPair");
	}

	public CryptoKeyPair findByKeyId(String keyId) {
		Map<String, CryptoKeyPair> map = redisService.getCacheMap("cryptoKeyPair");
		CryptoKeyPair cryptoKeyPair = map.get(keyId);
		if (cryptoKeyPair == null) {
			throw new BusinessException("公钥失效，请重新获取");
		}
		return cryptoKeyPair;
	}

	/**
	 * 保存密钥
	 *
	 * @param cryptoKeyPair 密钥实体
	 */
	public void saveKey(CryptoKeyPair cryptoKeyPair) {
		Map<String, CryptoKeyPair> map = new HashMap<>();
		map.put(cryptoKeyPair.getKeyId(), cryptoKeyPair);
		if (redisService.hasKey("cryptoKeyPair")) {
			redisService.deleteObject("cryptoKeyPair");
		}
		redisService.setCacheMap("cryptoKeyPair", map);
	}

	/**
	 * 删除
	 *
	 * @param keyId keyId
	 */
	public void deleteKey(String keyId) {
		redisService.deleteMap("cryptoKeyPair", keyId);
	}
}
